-- 游戏逻辑模块

local skynet = require "skynet"
local base = require "base"
local timetool = require "timetool"
local timer = require "timer"
local filelog = require "filelog"
local tabletool = require "tabletool"
local configdao = require "configdao"

local json = require "cjson"
json.encode_sparse_array(true, 1, 1)

require "lhjenum"

local GameLogic = { }
local service = nil
local tablelogic = nil
local seatlogic = nil

--[Comment]
--init 初始化
function GameLogic.init(caller)
	service = caller
	tablelogic = service:get_logicbyname("tablelogic")
	seatlogic = service:get_logicbyname("seatlogic")
end

--[Comment]
--初始化数据,主要设置游戏状态事件对应的函数
--
function GameLogic.init_data(gameobj, tableobj)
	gameobj.tableobj = tableobj
	gameobj.stateevent[ELHJTableState.TABLE_STATE_GAME_START] =  GameLogic.gamestart                         --游戏开始
	gameobj.stateevent[ELHJTableState.TABLE_STATE_ONE_GAME_START] = GameLogic.onegamestart                   --一局游戏开始
    gameobj.stateevent[ELHJTableState.TABLE_STATE_DO_SPIN] = GameLogic.dospin                                --执行转动
    gameobj.stateevent[ELHJTableState.TABLE_STATE_HANDLE_SPIN_RESULT] = GameLogic.handlespinresult           --处理转动结果
	gameobj.stateevent[ELHJTableState.TABLE_STATE_ONE_GAME_END] = GameLogic.onegameend                       --一局游戏结束
	gameobj.stateevent[ELHJTableState.TABLE_STATE_ONE_GAME_REAL_END] = GameLogic.onegamerealend              --一局游戏真正结束
    gameobj.stateevent[ELHJTableState.TABLE_STATE_GAME_END] = GameLogic.gameend                              --游戏结束

    --初始化游戏记录
    GameLogic.init_game_records(tableobj)

    --初始化线数组
    tableobj.line_list = skynet.call(".slotmgr","lua","get_line_list")
    tableobj.max_line_num = #(tableobj.line_list)

    --初始化picture_list
    tableobj.init_picture_list = skynet.call(".slotmgr","lua","get_init_picture_list")

	return true
end

--[Comment]
-- 运行游戏，不断执行状态事件,外部接口
--
function GameLogic.run(gameobj)
	local f = nil
	while true do
        --如果未全部准备，退出
		if gameobj.tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ALL_READY then
			break
		end

		f = gameobj.stateevent[gameobj.tableobj.state]  --获得桌子状态对应方法
		if f == nil then
			break
		end
		f(gameobj)  --执行

        --更新心跳时间
        tablelogic.update_table_heart_time(gameobj.tableobj)
	end
end

---------------------------------------------------------
---------------------------------------------------------
--游戏逻辑处理函数
--

--[Comment]
-- TABLE_STATE_GAME_START
-- 游戏开始
-- 游戏开始---一局游戏开始---游戏----一局游戏结束----一局游戏开始---游戏--一局游戏结束--...--游戏结束
-- gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.gamestart(gameobj)
	local tableobj = gameobj.tableobj

	GameLogic.gamestart_inittable(gameobj)
	tableobj.state = ELHJTableState.TABLE_STATE_ONE_GAME_START
    --执行完后将调用onegamestart

	--设置桌子已经开局
	tableobj.is_had_start = true
end

--[Comment]
--  一局游戏开始
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.onegamestart(gameobj)
	local tableobj = gameobj.tableobj

    --如果玩家已离开，则立即处理
    if tableobj.had_leave then
        tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_START
        return
    end

    --一初始化游戏
	GameLogic.onegamestart_inittable(gameobj)

    --当前局数 + 1
	tableobj.curr_to_num = tableobj.curr_to_num + 1	
    
    --初始化游戏记录
    GameLogic.onegamestart_init_tablerecord(gameobj)

    --通知client游戏开始
	GameLogic.send_gamestart_notice(gameobj)


    --倒计时等待旋转
	tableobj.state = ELHJTableState.TABLE_STATE_WAIT_DO_SPIN
	local timer_id = timer.settimer(5, "dospin")	
	if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_DO_SPIN then
		timer.cleartimer(timer_id)
	else
		tableobj.timer_id = timer_id
	end

    --如果玩家已离开，则立即处理
    if tableobj.had_leave then
        if tableobj.timer_id > 0 then
            timer.cleartimer(timer_id)
        end
        tableobj.timer_id = -1
        tableobj.state = ELHJTableState.TABLE_STATE_DO_SPIN
        return
    end
end

--[Comment]
--
--转动
--
function GameLogic.dospin(gameobj)
    local tableobj = gameobj.tableobj
    local seat = tableobj.seats[1]
    local gamename = tablelogic.get_gamename(tableobj)

    --获得随机结果
    local cur_real_score = seat.cur_base_score * seat.cur_multi_num
    local result_picture_list = skynet.call(".slotmgr","lua","get_random_spin_result",gamename, cur_real_score, seat.cur_line_num)
    if result_picture_list then
        tableobj.result_picture_list = result_picture_list
    end

    --如果玩家已离开，则立即处理
    if tableobj.had_leave then
        tableobj.state = ELHJTableState.TABLE_STATE_HANDLE_SPIN_RESULT
        return
    end
    
    --立即处理开奖结果
    tableobj.state = ELHJTableState.TABLE_STATE_HANDLE_SPIN_RESULT

    --通知玩家
    --[[
    local noticemsg = {
        init_picture_list = tableobj.init_picture_list,
        end_picture_list = tableobj.result_picture_list,
    }
    tablelogic.sendmsg_to_alltableplayer(tableobj, "dospinN", noticemsg)

    --等待5s
    tableobj.state = ELHJTableState.TABLE_STATE_WAIT_HANDLE_SPIN_RESULT
	local timer_id = timer.settimer(3 * 100, "handle_spinresult")	
	if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_HANDLE_SPIN_RESULT then
		timer.cleartimer(timer_id)
	else
		tableobj.timer_id = timer_id
	end
    --]]
end     

--[Comment]
--
--处理转动结果
--
function GameLogic.handlespinresult(gameobj)
    local tableobj = gameobj.tableobj
    local picture_list = tableobj.result_picture_list

    --检查玩家压注线中奖情况
    for _,seat in pairs(tableobj.seats) do
        if GameLogic.is_ingame(gameobj,seat) then
            local result_list = skynet.call(".slotmgr","lua","check_betlines_result",seat.cur_line_num, picture_list,true)
            tableobj.spin_result = result_list.spin_result
            tableobj.littemary_prize_list = result_list.littemary_prize_list
            break
        end
    end
    
    --计算每线得分
    local total_score = 0
    local seat = tableobj.seats[1]
    local fee_rate = tableobj.service_fee_rate or 0
    local base_score = seat.cur_base_score * seat.cur_multi_num
    for _,item in pairs(tableobj.spin_result) do
        local id = item.prize_id
        item.score = base_score * (tableobj.odds_list[id] or 0)
        total_score = total_score + item.score
    end
    for _,item in pairs(tableobj.littemary_prize_list) do
        total_score = total_score + base_score * (item.total_multi or 0)
    end
    
    local real_score = total_score
    if total_score > 0 then --赢家抽水
        total_score = total_score - math.floor(total_score * fee_rate * 2)
    end

    --如果玩家已离开，则立即结算
    if tableobj.had_leave then
        tableobj.state = ELHJTableState.TABLE_STATE_ONE_GAME_END
        return
    end

    --通知玩家
    local noticemsg = {
        init_picture_list = tableobj.init_picture_list,
        end_picture_list = tableobj.result_picture_list,
        spin_result = tableobj.spin_result,
        littemary_prize_list = tableobj.littemary_prize_list,
        total_score = total_score,
        real_score = real_score,
    }
    tablelogic.sendmsg_to_alltableplayer(tableobj, "dospinN", noticemsg)
    
    --如果本局得分，则等待玩家选择比倍或得分
    local delay = 20
    if #(tableobj.littemary_prize_list) == 0 and total_score > 0 then
        delay = 3000
        tableobj.is_wait_comp_multi = true
        tableobj.add_multi_num = 1    --加倍数
    end
    tableobj.cur_total_score = real_score

    --通知玩家
    --[[
    local noticemsg = {
       spin_result = tableobj.spin_result,
    }
    tablelogic.sendmsg_to_alltableplayer(tableobj, "spinresultN", noticemsg)
    --]]
    
    --等待3s
    tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END
	local timer_id = timer.settimer(delay, "onegameend")	
	if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END then
		timer.cleartimer(timer_id)
	else
		tableobj.timer_id = timer_id
	end
end       

--[Comment]
--  处理下注
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.handle_dobet(gameobj)
    local tableobj = gameobj.tableobj
    local seat = tableobj.seats[1]
    local gamename = tablelogic.get_gamename(tableobj)
    local base_score = seat.cur_base_score * seat.cur_multi_num
    local total_score = tableobj.cur_total_score or 0
    local bet_item_id = tableobj.cur_bet_item_id
    local line_num = seat.cur_line_num or 9
    local fee_rate = tableobj.service_fee_rate or 0
    
    --获取随机骰子点数
    local result_list = skynet.call(".slotmgr", "lua", "get_random_dices_result", gamename, total_score, bet_item_id, base_score, line_num)
    if result_list and result_list.prize_id == bet_item_id then
        total_score = total_score * ELHJDicesOddsList[bet_item_id]
        tableobj.add_multi_num = tableobj.add_multi_num * ELHJDicesOddsList[bet_item_id]
    else
        total_score = 0
        tableobj.add_multi_num = 0
    end
        
    local real_score = total_score
    if total_score > 0 then --赢家抽水
        total_score = total_score - math.floor(total_score * fee_rate * 2)
    end
    tableobj.cur_total_score = real_score
    tableobj.cur_bet_item_id = nil
    
    --通知摇骰子结果
    local noticemsg = {
        bet_item_id = bet_item_id,
        prize_id = result_list.prize_id,
        dice_one = result_list.dice_one,
        dice_two = result_list.dice_two,
        total_score = total_score,
        real_score = real_score,
    }
    tablelogic.sendmsg_to_alltableplayer(tableobj, "dobetN", noticemsg)
    
    --没押中结束游戏
    local delay = 20
    if total_score == 0 then
        tableobj.is_compare_multiing = nil
        tableobj.is_wait_comp_multi = nil
    else
        delay = 2500
    end
    
    --等待3s
    tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END
    local timer_id = timer.settimer(delay, "onegameend")	
    if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END then
        timer.cleartimer(timer_id)
    else
        tableobj.timer_id = timer_id
    end

end

--[Comment]
--  一局游戏结束
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.onegameend(gameobj)
    local tableobj = gameobj.tableobj
    
    tableobj.is_compare_multiing = nil
    tableobj.is_wait_comp_multi = nil

    --保存结束时间
    tableobj.one_end_time = timetool.get_time()

	--清空计时器
	if tableobj.timer_id > 0 then
		timer.cleartimer(tableobj.timer_id)
		tableobj.timer_id = -1
	end

	--一轮游戏结算
    GameLogic.onegameend_balance(gameobj)

    --更改每个座位总分
	for _, seat in pairs(tableobj.seats) do
		if not seatlogic.is_empty(seat) then
			seat.total_score = seat.total_score + seat.balance_score
		end
	end

    --设置桌子状态为：一局游戏真正结束
	tableobj.state = ELHJTableState.TABLE_STATE_ONE_GAME_REAL_END
end

--[Comment]
--  一局游戏真正结束
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.onegamerealend(gameobj)
	local tableobj = gameobj.tableobj

    --tableobj.is_onegameend = true
   
    --通知结算金钱变化
    if tablelogic.is_diamondtable() then
        GameLogic.game_balance_diamond(gameobj)
    end

    --保存牌局记录
    GameLogic.onegameend_save_tablerecord(gameobj)
    
    --获得游戏结果
	local noticemsg = tabletool.deepcopy(GameLogic.get_game_result(gameobj))

    --向机器人服务更新游戏数据
    --GameLogic.send_gameinfo_to_robotmgr(gameobj)

    --重置桌子数据,座位数据
	GameLogic.onegameend_inittable(gameobj)

    --获得重置之后的桌子信息,客户端清空桌子数据用
    noticemsg.table_gameinfo = tablelogic.copy_table_gameinfo()

     --发送结算
     if not tableobj.had_leave then
        tablelogic.sendmsg_to_alltableplayer(tableobj,"gamebalanceN",noticemsg)
     end
    
    --设置了结束标记,删除桌子
    if tableobj.tableend_flag then
        skynet.call(tableobj.table_service,"lua","cmd","delete",ELHJTableDeleteReason.DELETE_REASON_SYSTEM_REQUIRE)
        return
    end

    --空桌子
    if tableobj.sitdown_player_num <= 0 then
        tableobj.state = ELHJTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
        return
    end

    --等待一局开始
    tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_START
    if tableobj.had_leave then
        tableobj.is_ingame = false
        tableobj.is_onegameend = true
        return
    end

    --检测是否断线，断线取消自动开始
    if tableobj.is_auto_start and tableobj.seats[1] then
        local seat = tableobj.seats[1]
        if seat.is_disconnected then
            tableobj.is_auto_start = false
        end
    end
    
    --设置了自动开始，则延时3s后自动开始
    if false then
        --钱不够，则取消自动开始
        for _,seat in pairs(tableobj.seats) do
            if not seatlogic.is_empty(seat) then
                local coin = tablelogic.get_curmoney(seat)
                if seat.cur_total_bet > coin then
                    tableobj.is_auto_start = false
                    tablelogic.sendmsg_to_tableplayer(seat.rid,"notenoughmoneyN",{rid = seat.rid, seat_index = seat.index})
                    return
                end
            end
        end
        
	    local timer_id = timer.settimer(2 * 100, "onegamestart")	
	    if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_START then
		    timer.cleartimer(timer_id)
	    else
		    tableobj.timer_id = timer_id
            tableobj.is_will_auto_start = true
	    end
    end
    
    --等待客户端结束
    tableobj.timer_id = timer.settimer(5, "wait_clientgameend")
    if tableobj.timer_id == -1 then
        filelog.sys_error("------error timer id------")
    end
    --filelog.sys_info("----set timer----",tableobj.timer_id)
    
    return
end

--[Comment]
--  游戏结束
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.gameend(gameobj)
	local tableobj = gameobj.tableobj

	tableobj.state = ELHJTableState.TABLE_STATE_UNKNOW   --设置桌子状态为：未知
    if tableobj.game_records ~= nil then
	    tableobj.game_records.end_time = tableobj.end_time or timetool.get_time()
	    tableobj.game_records.final_to_num = tableobj.curr_to_num    --最终局数
        if tableobj.game_records.delete_reason == ELHJTableDeleteReason.DELETE_REASON_IN_GAME_DISBAND then
            tableobj.game_records.final_to_num = tableobj.game_records.final_to_num - 1
        end
    end

	--强制踢掉玩家
    if tablelogic.get_sitdown_player_num(tableobj) > 0 then
		tablelogic.leavetableallplayer(tableobj, EStandupReason.STANDUP_REASON_DELETE_TABLE)
		local waits = tabletool.deepcopy(tableobj.waits)
		for rid, waitinfo in pairs(waits) do
			tablelogic.passive_leavetable(tableobj, rid,waitinfo.playerinfo.diamond)
		end
	end

	--检查桌子当前是否能够删除
	if tableobj.delete_table_timer_id <= 0 then
		tableobj.delete_table_timer_id = -1
	end

    tableobj.is_had_start = false

    --倒计时删除,1s
    if tableobj.delete_table_timer_id == -1 then
        tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
    end
end

------------------------------------------------------------------
----其他方法

--[Comment]
--  坐下
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.on_sitdown_table(gameobj, seat)
    local tableobj = gameobj.tableobj
	if tableobj.delete_table_timer_id > 0 then
		timer.cleartimer(tableobj.delete_table_timer_id)
		tableobj.delete_table_timer_id = -1
	end
    tableobj.had_leave = nil
    tableobj.is_auto_start = nil
end

--[Comment]
--  等待坐下
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.wait_player_sitdown(gameobj)
	local tableobj = gameobj.tableobj
    if tableobj.sitdown_player_num <= 0 and tableobj.cur_watch_playernum <= 0 then
        if tableobj.delete_table_timer_id > 0 then
			timer.cleartimer(tableobj.delete_table_timer_id)
			tableobj.delete_table_timer_id = -1
		end
        --倒计时删除桌子
 		tableobj.delete_table_timer_id = timer.settimer(600 * 100, "delete_table")
    end
end


-----------------------------
--init类

--[Comment]
-- 第一局游戏开始时，初始化桌子
--
function GameLogic.gamestart_inittable(gameobj)
    --tableobj即table_data
	local tableobj = gameobj.tableobj

    --初始化桌子数据
	tableobj.end_time = 0                       --桌子结束时间
    tableobj.start_time = timetool.get_time()   --游戏开始时间
	tableobj.isdeleting = false                 --是否将被删除
	tableobj.is_onegameend = false              --是否一局游戏结束

    --保存游戏记录
    if tableobj.game_records then
        tableobj.game_records.start_time = tableobj.start_time
    end
end

--[Comment]
-- 每局游戏开始时，初始化桌子
--
function GameLogic.onegamestart_inittable(gameobj)
	local tableobj = gameobj.tableobj
	local now = timetool.get_time()

	tableobj.one_start_time =  now          --本局开始时间
    tableobj.one_end_time = 0               --本局结束时间
    tableobj.action_timeout_time = 0        --当前操作超时时间

    --本局局号
    tableobj.curr_round_code = string.format("%04d",now % 10000)

    --一局结束的标记
	tableobj.is_onegameend = false              --是否一局结束
    tableobj.is_ingame = true                   --是否游戏中
    tableobj.had_leave = nil                    --是否玩家已离开
    tableobj.spin_result = nil                  --旋转结果
    tableobj.is_will_auto_start = false         --是否即将自动开始
    
    --重新获取抽水率
    local gamename = tablelogic.get_gamename(tableobj)
    local status,cur_rate = skynet.pcall(skynet.call, ".slotmgr", "lua", "get_service_fee_rate", gamename)
    if status and cur_rate then
        tableobj.service_fee_rate = tonumber(cur_rate) or 0.03
    end

    --初始化座位
    for _,seat in pairs(tableobj.seats) do
        if not seatlogic.is_empty(seat) and seat.had_ready then
            seatlogic.onegamestart_initseat(seat)
        end
    end
    
    --重置通用计时器
	if tableobj.timer_id >= 0 then
		timer.cleartimer(tableobj.timer_id)
		tableobj.timer_id = -1
	end

    tableobj.has_resettable = nil

end

--[Comment]
-- 每局游戏结束时，初始化桌子
--
function GameLogic.onegameend_inittable(gameobj)
	local tableobj = gameobj.tableobj

    tableobj.one_start_time = 0	      --开始时间要先清空，游戏开始时再设置
    --tableobj.is_ingame = false        --是否游戏中
    tableobj.curr_round_code = ""
    tableobj.init_picture_list = tableobj.result_picture_list   --初始图片数组
    tableobj.result_picture_list = nil                          --结果图片数组

    --重新获取奖池金额
    local gamename = tablelogic.get_gamename(tableobj)
    tableobj.cur_jackpot_money = skynet.call(".jackpotmgr", "lua", "get_jackpot_money", gamename, tableobj.cur_jackpot_id)
    
    --初始化座位
    for _,seat in pairs(tableobj.seats) do
        if not seatlogic.is_empty(seat) and seat.had_ready then
            seatlogic.onegameend_initseat(seat)
        end
    end

    if tableobj.timer_id >= 0 then
		timer.cleartimer(tableobj.timer_id)
		tableobj.timer_id = -1
	end

end

--[Comment]
-- 初始化游戏记录(桌子创建时便被调用）
--
function GameLogic.init_game_records(tableobj)
    --游戏记录表（记录游戏数据）
	tableobj.game_records = { 
        --固定信息
        table_type = tableobj.table_type,               --桌子类型
		table_uuid = tableobj.uuid,                     --桌子uuid
        create_user_rid = tableobj.create_rid,          --创建者rid
        conf = tableobj.conf or { },                    --桌子配置
        delete_reason = 0,                              --删除原因
		create_time = tableobj.create_time,             --创建时间
        delete_time = 0,                                --删除时间
        start_time = 0,                                 --第一局开始时间
        end_time =  0,                                  --最后一局结束时间
		final_to_num = 0,                               --最终局数
        table_code = tableobj.code,                     --桌号
	}

end

--[Comment]
--游戏开始初始化牌局记录
--
function GameLogic.onegamestart_init_tablerecord(gameobj)
    local tableobj = gameobj.tableobj
    local rids = { }

    --每局信息
    tableobj.game_records.cur_record_id = ""                             --本局记录日志id（log日志文件名）
    tableobj.game_records.curr_to_num = tableobj.curr_to_num or 0        --当前局数
    tableobj.game_records.one_start_time = tableobj.one_start_time or 0  --本局开始时间
    tableobj.game_records.one_end_time = 0                               --本局结束时间
    tableobj.game_records.table_tradeid = ""                             --本局唯一交易id
    tableobj.game_records.players_balance_list = {}                      --本局结算情况
    tableobj.game_records.sys_diamond_start = 0                          --系统开始钻石
    tableobj.game_records.sys_diamond_end = 0                            --系统结束钻石
    tableobj.game_records.user_count = 0                                 --游戏总人数
    tableobj.game_records.banker_seat_index = tableobj.banker_seat_index or 0       --庄家位置
    tableobj.game_records.role_info = { }                                           --玩家信息

    --初始化玩家信息
    for _,seat in pairs(tableobj.seats) do
        if GameLogic.is_ingame(gameobj,seat) then
            local item = {
                sex = seat.playerinfo.sex,
                diamond = seat.playerinfo.diamond,
                coin = seat.playerinfo.coin,
                name = seat.playerinfo.rolename,
                logo = seat.playerinfo.logo,
                seat_index = seat.index,
             }
            tableobj.game_records.role_info[seat.rid] = item
        end
    end
                     
    --玩家开始前金钱情况
    tableobj.game_records.diamond_change_list = {}  
    tableobj.game_records.coin_change_list = {}                                 
    for _,seat in pairs(tableobj.seats) do
        if GameLogic.is_ingame(gameobj,seat) then
            local item = { }
            item.gamestart_diamond = seat.playerinfo.diamond
            tableobj.game_records.diamond_change_list[seat.rid] = item
            tableobj.game_records.coin_change_list[seat.rid] = {gamestart_coin = seat.playerinfo.coin}
            table.insert(rids,seat.rid)
        end
    end

    --获得rid的升序序列
    table.sort(rids)
    tableobj.seq_rids = ""
    for _,rid in pairs(rids) do
        tableobj.seq_rids = tableobj.seq_rids .. rid .. "_"
    end
end

--[Comment]
--游戏结束更新牌局记录
--
function GameLogic.onegameend_save_tablerecord(gameobj)
    local tableobj = gameobj.tableobj
    local total_bet = 0

    --修改牌局记录
	if tableobj.game_records ~= nil then
        local game_records = tableobj.game_records
        game_records.user_count = 0
        game_records.one_end_time = tableobj.one_end_time or 0
        game_records.table_tradeid = tableobj.cur_table_tradeid or ""
        game_records.init_picture_list = tableobj.init_picture_list
        game_records.result_picture_list = tableobj.result_picture_list
        game_records.spin_result = tableobj.spin_result
        
        --钻石变化
        local record_id = game_records.table_uuid .. "_"
        record_id = record_id .. game_records.one_start_time .. "_"
        record_id = record_id .. game_records.one_end_time .. "_"
		record_id = record_id .. tableobj.seq_rids
        for _,seat in pairs(tableobj.seats) do
            if GameLogic.is_ingame(gameobj, seat) then
                --金钱变化
                local ditem = game_records.diamond_change_list[seat.rid]
                local citem = game_records.coin_change_list[seat.rid]
                if not ditem then
                    game_records.diamond_change_list[seat.rid] = {gamestart_diamond = seat.playerinfo.diamond}
                    ditem = game_records.diamond_change_list[seat.rid]
                end
                if not citem then
                    game_records.coin_change_list[seat.rid] = {gamestart_coin = seat.playerinfo.coin}
                    citem = game_records.coin_change_list[seat.rid]
                end
                citem.winvalue = seat.playerinfo.coin - citem.gamestart_coin
                ditem.winvalue = seat.playerinfo.diamond - ditem.gamestart_diamond
                citem.gameend_coin = seat.playerinfo.coin
                ditem.gameend_diamond = seat.playerinfo.diamond

                --个人信息
                if not game_records.role_info[seat.rid] then
                    game_records.role_info[seat.rid] = {
                        sex = seat.playerinfo.sex,
                        diamond = seat.playerinfo.diamond,
                        coin = seat.playerinfo.coin,
                        name = seat.playerinfo.rolename,
                        logo = seat.playerinfo.logo,
                        seat_index = seat.index,
                    }
                end

                --结算
                if seat.state == ELHJSeatState.SEAT_STATE_PLAYING then
                    if seat.is_robot then
                        game_records.user_count = game_records.user_count - 1
                    else
                        --结算相关
                        local balance_list = { }
                        --玩家rid
                        balance_list.rid = seat.rid
                        --本局下注
                        balance_list.diamond = seat.cur_total_bet
                        total_bet = seat.cur_total_bet or 0
                        --输赢钻石数
                        balance_list.diamond_change = seat.balance_score or 0
                        --输赢状态，1：赢 0：输
                        if balance_list.diamond_change < 0 then
                            balance_list.state = 0
                        else
                            balance_list.state = 1
                        end
                        table.insert(game_records.players_balance_list,balance_list)
                        game_records.user_count = game_records.user_count + 1
                    end
                end
            end
        end
        record_id = record_id .. os.date("%Y%m%d_%H%M%S",game_records.one_start_time)
        game_records.cur_record_id = record_id
	end
    
    --写到日志
    if total_bet >= 9000 then
        tablelogic.save_table_records(tableobj.game_records)
    end
end

-----------------------------------------------------------------------------
---check类
--

--[Comment]
--  检查玩家钱是否足够
--  gameobj 游戏对象，{stateevent,tableobj}
--
function  GameLogic.check_player_money(tableobj,seat)
    local min_carry_amount = tableobj.conf.min_carry_amount or 0
    local max_carry_amount = tableobj.conf.max_carry_amount or 0

    if not seat then
        return false
    end

    local money = tablelogic.get_curmoney(seat)
    if money < min_carry_amount or money > max_carry_amount then
        return false
    end

    return true
end

------------------------------------------------------------------------
--通知类方法
--

--[Comment]
--  通知所有玩家游戏开始
--  gameobj 游戏对象，{stateevent,tableobj}
--
 function GameLogic.send_gamestart_notice(gameobj)
	local tableobj = gameobj.tableobj
	local noticemsg = { }

    noticemsg.curr_to_num = tableobj.curr_to_num                --当前局数
    noticemsg.seat_roleinfos = { }
    noticemsg.seat_gameinfos = { }
    for index,seat in pairs(tableobj.seats) do
		noticemsg.seat_roleinfos[index] = tablelogic.copy_seat_roleinfo(seat)
		noticemsg.seat_gameinfos[index] = tablelogic.copy_seat_gameinfo(seat)
	end
	tablelogic.sendmsg_to_alltableplayer(tableobj,"gamestartN", noticemsg)
 end

--[Comment]
--  通知所有玩家一局游戏结束
--  gameobj 游戏对象，{stateevent,tableobj}
--
 function GameLogic.send_onegameend_notice(gameobj)
	local tableobj = gameobj.tableobj
	local noticemsg = { }

    noticemsg.table_index = tableobj.index    --桌号
	tablelogic.sendmsg_to_alltableplayer(tableobj,"onegameendN", noticemsg)
 end

 --[Comment]
--  通知所有玩家游戏结束
--  gameobj 游戏对象，{stateevent,tableobj}
--
 function GameLogic.send_gameend_notice(gameobj)
	local tableobj = gameobj.tableobj
	local noticemsg = { }

    noticemsg.table_index = tableobj.index    --桌号
	tablelogic.sendmsg_to_alltableplayer(tableobj,"gameendN", noticemsg)
 end

------------------------------------------------------------------------
---修改数据类
--

--[Comment]
-- 重置桌子数据
--
function GameLogic.reset_tabledata(gameobj)
	local tableobj = gameobj.tableobj

    if tableobj.has_resettable then
        return
    end

    --初始化桌子数据
	tableobj.end_time = 0                       --桌子结束时间
	tableobj.isdeleting = false                 --是否将被删除
	tableobj.is_onegameend = false              --是否一局游戏结束
    tableobj.has_resettable = true
end


-----------------------------------------------------------
--clear类
--

--[Comment]
-- 站起后，删除座位对象
--
function GameLogic.standup_clear_seat(gameobj, seat)
    local tableobj = gameobj.tableobj
	seatlogic.clear_seat(seat)
end

---------------------------------------------------------------
---is类
--

--[Comment]
--判断座位对应玩家是否在游戏中
--
function GameLogic.is_ingame(gameobj, seat)
	return (seat.state > ELHJSeatState.SEAT_STATE_WAIT_START)
end

------------------------------------------------------------
---get类
--

--[Comment]
--  通知结算信息
--  gameobj 游戏对象，{stateevent,tableobj}
--
function GameLogic.get_game_result(gameobj)
	local tableobj = gameobj.tableobj

	--通知游戏结算
	local noticemsg = {
		table_index = tableobj.index,                   --桌子id
        create_rid = tableobj.create_rid,               --创建者rid
        create_rolename = tableobj.create_rolename,     --创建者名字
		curr_to_num = tableobj.curr_to_num,             --当前局数
		one_start_time = tableobj.one_start_time,       --本局开始时间
        one_end_time = tableobj.one_end_time,           --本局结束时间
		table_type = tableobj.conf.table_type,          --桌子类型
		playergameresultlist = {                        --所有玩家的结算列表
		}

	}
	
    --获得每个座位结算信息
	local playergameresultitem = nil
	for index, seat in pairs(tableobj.seats) do
		if GameLogic.is_ingame(gameobj, seat) then
			playergameresultitem = {   --结算信息
				rid = seat.rid,
                seat_index = seat.index,
				rolename = seat.playerinfo.rolename,
				logo = seat.playerinfo.logo,
				curr_score = seat.curr_score,
	 			total_score = seat.total_score,
			}
            table.insert(noticemsg.playergameresultlist,playergameresultitem)
		end	
	end

    return noticemsg
end

--[Comment]
--获得游戏中玩家数
--
function GameLogic.get_ingame_playernum(gameobj)
	local tableobj = gameobj.tableobj
	local playernum = 0
	for _, seat in pairs(tableobj.seats) do
		if GameLogic.is_ingame(gameobj, seat) then
			playernum = playernum + 1
		end
	end
	return playernum
end

------------------------------------------------------------
---结算类
--

--[Comment]
--@ des 一轮结算
--@ gameobj 游戏对象
--
function GameLogic.onegameend_balance(gameobj)
    local tableobj = gameobj.tableobj
    local odds_list = tableobj.odds_list
    local seat = tableobj.seats[1]  --只有1个玩家

    --计算得分
    local total_score = 0
    local fee_rate = tableobj.service_fee_rate or 0
    for _,item in pairs(tableobj.spin_result) do
        local id = item.prize_id
        total_score = total_score + seat.cur_multi_num * seat.cur_base_score * (odds_list[id] or 0)
    end
    for _,item in pairs(tableobj.littemary_prize_list) do
        total_score = total_score + seat.cur_multi_num * seat.cur_base_score * (item.total_multi or 0)
    end
    total_score = total_score * (tableobj.add_multi_num or 1)
    seat.curr_score = total_score - seat.cur_total_bet
    seat.balance_score = seat.curr_score
    if total_score > 0 then --赢家抽水
        seat.balance_score = seat.balance_score - math.floor(total_score * fee_rate * 2)
    end
    
    --保存记录
    GameLogic.save_records(tableobj)
end

--[Comment]
--保存记录
--
function GameLogic.save_records(tableobj)
    local gamename = tablelogic.get_gamename(tableobj)
    skynet.send(".slotmgr","lua","save_prize_records",gamename, tableobj.spin_result)
end

--[Comment]
--@ des 钻石场游戏结算
--@ gameobj 游戏对象
--
function GameLogic.game_balance_diamond(gameobj)
    local tableobj = gameobj.tableobj
    local noticemsg = { }
    noticemsg.money_change_list = { }

    local rid_values = { }
    local rid_to_index = { }
    for i,seat in pairs(tableobj.seats) do
        if seat.state == ELHJSeatState.SEAT_STATE_PLAYING then
            local change_value = (seat.balance_score or 0)
            rid_values[seat.rid] = {}
            rid_values[seat.rid].beginvalue = seat.playerinfo.diamond
            rid_values[seat.rid].value = change_value
            rid_values[seat.rid].endvalue = rid_values[seat.rid].beginvalue + rid_values[seat.rid].value
            rid_values[seat.rid].real_change = seat.curr_score
            rid_values[seat.rid].total_bet = seat.cur_total_bet
            rid_values[seat.rid].level = seat.playerinfo.level
            rid_to_index[seat.rid] = i
        end
    end

    --通知gate去扣费
    local status,comment = tablelogic.game_balance_diamond(rid_values)
    if not status then
        filelog.sys_error("game balance diamond failed!")
        return false
    else
        filelog.sys_info("game balance diamond ok!")
    end
    tableobj.cur_table_tradeid = comment.table_tradeid or ""

    --扣费成功，修改数据
    for rid,rv in pairs(rid_values) do
        local tmpseat = tableobj.seats[rid_to_index[rid]]
        tmpseat.playerinfo.diamond = tmpseat.playerinfo.diamond + rv.value
        local item = { 
            rid = rid,
            money_type = EMoneyType.DIAMOND, --金钱类型：1金币 2钻石
        }
        item.final_value = rv.endvalue
        item.change_value = rv.value
        table.insert(noticemsg.money_change_list,item)
    end

    --通知客户端
    tablelogic.sendmsg_to_alltableplayer(tableobj,"moneychangeN",noticemsg)
    
    return true
end

---------------------------------------------------------

return GameLogic

---游戏逻辑----